package middleware

import (
	"errors"
	"fmt"
	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/gin-gonic/gin"
	"net/http"
)

// SentinelCheck 熔断限流检查中间件，植入路由前验证
func SentinelCheck(ctx *gin.Context) {
	// 这里source特指请求url
	entry, blockError := sentinel.Entry(
		ctx.Request.URL.Path,
		sentinel.WithResourceType(base.ResTypeWeb), // 资源分类，这里设置为web
		sentinel.WithTrafficType(base.Inbound),     // 流量类型，这里主要是处理入口流量
	)
	if blockError != nil {
		ctx.String(http.StatusInternalServerError, fmt.Sprintf("触发熔断限流 [%+v] [%+v] ", ctx.Request.URL.Path, blockError.BlockMsg()))
		ctx.Abort()
		return
	}
	defer func() {
		entry.Exit()
	}()
	ctx.Next()
	if ctx.Writer.Status() != http.StatusOK {
		sentinel.TraceError(entry, errors.New("biz error"))
	}
}
